package com.canto.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 转换工具类
 *
 * @Author jsryin
 * @Date 2021/12/4
 */
public class ConvertUtil {

    /**
     * list映射为list 比如List<User> userList转为List<String> nameList
     *
     * @param list   原数据
     * @param mapper 转换规则
     * @param <T>    原数据类型
     * @param <R>    新数据类型
     * @return
     */
    public static <T, R> List<R> resultTolist(List<T> list, Function<T, R> mapper) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<R>();
        }

        List<R> result = new ArrayList<>(list.size());
        for (T originElement : list) {
            R newElement = mapper.apply(originElement);
            if (newElement == null) {
                continue;
            }
            result.add(newElement);
        }
        return result;
    }

    /**
     * List转Map
     *
     * @param list         原数据
     * @param keyExtractor 转换规则
     * @param <K>          key
     * @param <V>          value
     * @return
     */
    public static <K, V> Map<K, V> listToMap(List<V> list, Function<V, K> keyExtractor) {
        if (list == null || list.isEmpty()) {
            return new HashMap<>();
        }

        Map<K, V> map = new HashMap<>();
        for (V element : list) {
            K key = keyExtractor.apply(element);
            if (key == null) {
                continue;
            }
            map.put(key, element);
        }

        return map;
    }

}
